package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.Machine;
import com.example.domain.Order;
import com.example.domain.Pay;
import com.example.domain.Roll;
import com.example.exception.ServiceException;
import com.example.service.*;
import com.example.util.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
    @RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService service;

    @Autowired
    private MachineService machineService;

    @Autowired
    private OrderService orderService;

    @GetMapping("/list")
    public R list(Pay pay) {
        LambdaQueryWrapper<Pay> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(pay.getPaymentRecordId() != null, Pay::getPaymentRecordId, pay.getPaymentRecordId());
        List<Pay> list = service.list(wrapper);
        return R.data(list);
    }

    @PostMapping("/record")
    @Transactional
    public R save(@RequestParam("orderId") Integer orderId, @RequestParam("method") String method) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return R.fail("订单信息不存在");
        }
        Pay pay = new Pay();
        pay.setSno(order.getSno() + "");
        pay.setPaymentAmount(order.getTotalCost());
        pay.setPaymentMethod(method);
        pay.setPaymentDate(new Date());
        service.save(pay);
        order.setPaymentRecordId(pay.getPaymentRecordId());
        order.setCompletionTime(new Date());
        orderService.updateById(order);
        Machine machine = machineService.getByNumber(order.getMachineNumber());
        machine.setIdleStatus(0);
        machineService.updateById(machine);
        return R.success("操作成功");
    }
}
